<template>
  <div v-if="isShowHomeReport">
    <ContentWrap>
      <div class="flex flex-justify-between">
        <el-card shadow="never" class="w-100%">
          <div class="text-center">
            {{ preData.name }}
          </div>
          <div>
            <div v-for="(obj, objIndex) in menuList" :key="objIndex" class="mb-22px">
              <SubTitle :title="objectMap.get(obj.dataObj)" />
              <div class="chart-list" :id="`chart-box${objIndex}`">
                <div
                  v-for="(chart, chartIndex) in obj.temp"
                  :key="chartIndex"
                  :class="`${chart.type}-css`"
                  class="text-right"
                >
                  <!-- <el-button
                    :icon="Close"
                    size="small"
                    circle
                    @click="CloseChart(objIndex, chartIndex)"
                    class="ml-12px"
                  /> -->
                  <div v-if="chart.type == 'Table'">
                    <el-table :data="tableData[chart.dataObj]" class="mt-12px">
                      <el-table-column prop="name" label="名称" />
                      <el-table-column prop="dbCount" label="数据库资产" />
                      <el-table-column prop="fileCount" label="文件资产" />
                    </el-table>
                  </div>
                  <div v-if="chart.type == 'Pie'">
                    <Echart :height="300" :options="PieData[chart.dataObj][chart.dataType]" />
                  </div>
                  <div v-if="chart.type == 'Bar'">
                    <div class="flex flex-items-center" v-if="!reportId">
                      <div class="ml-auto mr-2">旋转</div>
                      <el-switch
                        class="mr-10"
                        v-model="chart.isReversed"
                        @change="reverseChange(chart)"
                      />
                    </div>
                    <Echart :height="300" :options="BarData[chart.dataObj][chart.dataType]" />
                  </div>
                  <div v-if="chart.type == 'Line'">
                    <Echart :height="300" :options="LineData[chart.dataObj][chart.dataType]" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </ContentWrap>
  </div>
</template>

<script lang="ts" setup>
import { set, cloneDeep } from 'lodash-es'
import SubTitle from '@/components/SubTitle/index.vue'
import Sortable from 'sortablejs'
import { Close } from '@element-plus/icons-vue'
import * as reportManageApi from '@/api/report/reportManage/index'
import * as reportTempApi from '@/api/report/reportTemp/index'
import { EChartsOption } from 'echarts'
import { barOptions, lineOptions, pieOptions } from './echarts-data'
const props = defineProps({
  reportId: String,
  startTime: String,
  endTime: String
})
const route = useRoute()
const preData = ref(route.query)
const menuList = ref([])
watch(
  () => props.reportId,
  (newValue) => {
    getReportManageGetShow()
  }
)
watch(
  () => props.startTime,
  (newValue) => {
    getReportManageGetShow()
  }
)

const tableInfo = reactive({
  columns: [
    { label: '名称', prop: 'name' },
    { label: '数据库资产', prop: 'dbCount' },
    { label: '文件资产', prop: 'fileCount' }
  ],
  data: []
})

const tableData = ref({
  StandardStatistics: []
})

const PieData = ref({
  StandardStatistics: {
    database: cloneDeep(pieOptions),
    file: cloneDeep(pieOptions)
  },
  ClassificationStatistics: {
    database: cloneDeep(pieOptions),
    file: cloneDeep(pieOptions)
  },
  LevelStatistics: {
    database: cloneDeep(pieOptions),
    file: cloneDeep(pieOptions)
  },
  SystemStatistics: {
    database: cloneDeep(pieOptions),
    file: cloneDeep(pieOptions)
  },
  DeptStatistics: {
    database: cloneDeep(pieOptions),
    file: cloneDeep(pieOptions)
  }
})
const LineData = ref({
  StandardStatistics: {
    database: cloneDeep(lineOptions),
    file: cloneDeep(lineOptions)
  },
  ClassificationStatistics: {
    database: cloneDeep(lineOptions),
    file: cloneDeep(lineOptions)
  },
  LevelStatistics: {
    database: cloneDeep(lineOptions),
    file: cloneDeep(lineOptions)
  },
  SystemStatistics: {
    database: cloneDeep(lineOptions),
    file: cloneDeep(lineOptions)
  },
  DeptStatistics: {
    database: cloneDeep(lineOptions),
    file: cloneDeep(lineOptions)
  }
})
const BarData = ref({
  StandardStatistics: {
    database: cloneDeep(barOptions),
    file: cloneDeep(barOptions)
  },
  ClassificationStatistics: {
    database: cloneDeep(barOptions),
    file: cloneDeep(barOptions)
  },
  LevelStatistics: {
    database: cloneDeep(barOptions),
    file: cloneDeep(barOptions)
  },
  SystemStatistics: {
    database: cloneDeep(barOptions),
    file: cloneDeep(barOptions)
  },
  DeptStatistics: {
    database: cloneDeep(barOptions),
    file: cloneDeep(barOptions)
  }
})

const CloseChart = (objIndex, chartIndex) => {
  menuList.value[objIndex].temp.splice(chartIndex, 1)
}

const convertData = (data) => {
  const menuList: any = []

  data.forEach((item) => {
    const temp: any = []
    item.view.forEach((viewItem) => {
      if (viewItem.chartsType === 'Table') {
        temp.push({
          type: 'Table',
          dataObj: item.dataObject
        })
      } else {
        temp.push({
          type: viewItem.chartsType,
          dataType: 'database',
          dataObj: item.dataObject
        })
        temp.push({
          type: viewItem.chartsType,
          dataType: 'file',
          dataObj: item.dataObject
        })
      }
    })

    menuList.push({
      dataObj: item.dataObject,
      temp: temp
    })
  })

  return menuList
}

// 数据对象列表
const dataObjectList = ref()
const objectMap = new Map([
  ['StandardStatistics', '数据保护标准'],
  ['ClassificationStatistics', '类别'],
  ['LevelStatistics', '级别'],
  ['SystemStatistics', '所属应用系统'],
  ['DeptStatistics', '归属机构']
])

const isShowHomeReport = ref(true)
const getDataObject = async () => {
  const data = await reportManageApi.reportManageDataObject()
  console.log('data', data)
  dataObjectList.value = data
  data.forEach((item) => {
    objectMap.set(item.key, item.value)
  })
  console.log('objectMap', objectMap)
  console.log("objectMap.get('LevelStatistics')", objectMap.get('LevelStatistics'))
}

const chartInfoData = ref()
const getReportManageGetShow = async () => {
  console.log('getReportManageGetShow')
  let data
  if (props.reportId) {
    data = await reportManageApi.reportManageGet({ id: props.reportId })
  } else if (props.startTime && props.endTime) {
    const params = {
      startTime: props.startTime,
      endTime: props.endTime
    }
    data = await reportManageApi.reportManageGetHomePage(params)
  } else {
    data = await reportManageApi.reportManageGetShow()
  }
  console.log('data', data)
  // menuList.value = convertData(data.tempVO)
  // 如果data为空，没有首页报表，那么隐藏首页报表模块
  if (!data) {
    isShowHomeReport.value = false
    return
  }
  menuList.value = JSON.parse(data?.composing)
  menuList.value.forEach((item) => {
    item.temp.forEach((subItem) => {
      if (subItem.type === 'Bar') {
        subItem.isReversed = false
      }
    })
  })
  chartInfoData.value = data?.data.context
  console.log('menuList.value', menuList.value)
  data?.data.context.forEach((item) => {
    // 表格
    tableData.value[item.dataObject] = item.viewData.Table
    // 饼状图
    if (item.viewData.Pie) {
      getPieChartData(
        PieData.value[item.dataObject].database,
        item.viewData.Pie,
        item.dataObject,
        'database'
      )
      getPieChartData(
        PieData.value[item.dataObject].file,
        item.viewData.Pie,
        item.dataObject,
        'file'
      )
    }
    // 折线图图
    if (item.dbLine) {
      getLineChartData(
        LineData.value[item.dataObject].database,
        item.dbLine,
        item.dataObject,
        'database'
      )
    }
    if (item.fileLine) {
      getLineChartData(LineData.value[item.dataObject].file, item.fileLine, item.dataObject, 'file')
    }
    // 柱状图
    if (item.viewData.Bar) {
      getBarChartData(
        BarData.value[item.dataObject].database,
        item.viewData.Bar,
        item.dataObject,
        'database'
      )
      getBarChartData(
        BarData.value[item.dataObject].file,
        item.viewData.Bar,
        item.dataObject,
        'file'
      )
    }
  })
}

const getPieChartData = (chartOption, chartData, dataObject, type) => {
  set(
    chartOption,
    'legend.data',
    chartData.map((v) => v.name)
  )
  set(chartOption, 'series', [
    {
      name: `${type == 'file' ? '文件资产' : '数据库资产'} ${objectMap.get(dataObject)}占比`,
      type: 'pie',
      radius: '55%',
      center: ['50%', '60%'],
      data: chartData.map((v) => {
        return {
          name: v.name,
          value: type == 'file' ? v.fileCount : v.dbCount
        }
      })
    }
  ])
  set(chartOption, 'title', {
    text: `${type == 'file' ? '文件资产' : '数据库资产'} ${objectMap.get(dataObject)}占比`,
    left: 'center'
  })
}
const reverseChange = (chart) => {
  const targetData = chartInfoData.value.find((item) => item.dataObject === chart.dataObj)
  console.log('targetData', targetData)
  getBarChartData(
    BarData.value[chart.dataObj][chart.dataType],
    targetData.viewData.Bar,
    chart.dataObj,
    chart.dataType,
    chart.isReversed
  )
}
const getBarChartData = (chartOption, chartData, dataObject, type, isReversed) => {
  // set(
  //   chartOption,
  //   'xAxis.data',
  //   chartData.map((v) => v.name)
  // )
  if (isReversed) {
    set(
      chartOption,
      'yAxis.data',
      chartData.map((v) => v.name)
    )
    set(chartOption, 'yAxis.type', 'category')

    set(
      chartOption,
      'xAxis.data',
      chartData.map((v) => (type === 'file' ? v.fileCount : v.dbCount))
    )
    set(chartOption, 'xAxis.type', 'value')
  } else {
    set(
      chartOption,
      'xAxis.data',
      chartData.map((v) => v.name)
    )
    set(chartOption, 'xAxis.type', 'category')

    set(
      chartOption,
      'yAxis.data',
      chartData.map((v) => (type === 'file' ? v.fileCount : v.dbCount))
    )
    set(chartOption, 'yAxis.type', 'value')
  }
  set(chartOption, 'series', [
    {
      type: 'bar',
      data: chartData.map((v) => {
        return {
          name: v.name,
          value: type == 'file' ? v.fileCount : v.dbCount
        }
      })
    }
  ])
  set(chartOption, 'title', {
    text: `${type == 'file' ? '文件资产' : '数据库资产'} ${objectMap.get(dataObject)}数量`,
    left: 'center'
  })
}
const getLineChartData = (chartOption, chartData, dataObject, type) => {
  set(chartOption, 'xAxis.data', chartData.time)
  chartData.items.map((e) => {})
  set(
    chartOption,
    'series',
    chartData.items.map((e) => {
      return {
        name: e.name,
        smooth: true,
        type: 'line',
        data: e.values,
        animationDuration: 500,
        animationEasing: 'cubicInOut'
      }
    })
  )
  set(chartOption, 'title', {
    text: `${type == 'file' ? '文件资产' : '数据库资产'} ${objectMap.get(dataObject)}周期趋势`,
    left: 'center'
  })
}

onMounted(() => {
  // 获取数据类别下拉
  getDataObject()
  getReportManageGetShow()
})
</script>
<style lang="scss">
.item {
  background: red;
}
.chart-wrap {
  width: calc(100% - 400px);
}
.chart-list {
  display: flex;
  flex-wrap: wrap;
}
.Table-css {
  width: 100%;
  margin-bottom: 12px;
  // height: 100px;
  // background-color: red;
}
.Pie-css {
  width: 50%;
  margin-bottom: 12px;
  height: 350px;
  // background-color: blue;
}
.Bar-css {
  width: 50%;
  margin-bottom: 12px;
  height: 350px;
  // background-color: green;
}
.Line-css {
  width: 50%;
  margin-bottom: 12px;
  height: 350px;
  // background-color: green;
}
:deep(table) {
  table-layout: auto !important;
}
:deep(.el-table__header-wrapper .el-table__header) {
  width: 100% !important;
}
:deep(.el-table__body-wrapper .el-table__body) {
  width: 100% !important;
}
</style>
